//
//  SYRefreshControl.swift
//  weibo
//
//  Created by sanya on 15/7/2.
//  Copyright © 2015年 sanya. All rights reserved.
//


import UIKit
import FFAutoLayout

class SYRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        addSubview(refreshView)
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 150, height: 60))
        // KVO 监听自己
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }
    /**
    1. 向下拉，y值会越来越小，Y值为负数，控件就会显示
    2. 拉到一定程度，会自动刷新
    3. 如果向上推表格，刷新控件仍然在，没有消失，Y值会一直变大
    */
    
    /// 显示提示图标标记
    private var showTipFlag = false
    
    private var loadingFlag = false
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit{
        // 注销监听
        removeObserver(self, forKeyPath: "frame")
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if frame.origin.y >  0{
//            refreshView.stopLoadingAnimation()
//            loadingFlag = false
            return
        }
        // 如果正在加载数据，就显示加载动画
        if refreshing && !loadingFlag {
            // 加载动画
            refreshView.startLoadingAnimation()
            loadingFlag = true
            return
            
        }
        
        // 向下转
        if frame.origin.y < -50 && !showTipFlag{
        
            print("向下转")
            
            showTipFlag = true
            refreshView.rotationTioIcon(showTipFlag)
        }
        // 转回去
        if frame.origin.y >= -50 && showTipFlag{
            print("转回去")
            showTipFlag = false
            refreshView.rotationTioIcon(showTipFlag)
        }
        
        
        
    }
    override func endRefreshing() {
        super.endRefreshing()
        // 关闭动画
        refreshView.stopLoadingAnimation()
        
        // 重新刷新标记
        loadingFlag = false
    }
    
    lazy var refreshView = SYRefreshView.refreshView()
}


class SYRefreshView:UIView {
    @IBOutlet weak var tipIcon: UIImageView!
    @IBOutlet weak var loadingIcon: UIImageView!
    @IBOutlet weak var tipView: UIView!
    class func refreshView() -> SYRefreshView{
        return NSBundle.mainBundle().loadNibNamed("SYRefreshView", owner: nil, options: nil).last as! SYRefreshView
    }
    /// 旋转提示图标
    private func rotationTioIcon(clock:Bool){
        var angle = M_PI
        angle += clock ? -0.01 :0.01
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, CGFloat(angle))
        }
    
    }
    /// 开启加载动画
    private func startLoadingAnimation() {
        tipView.hidden = true
        let anima = CABasicAnimation(keyPath: "transform.rotation")
        anima.toValue = 2 * M_PI
        anima.repeatCount = MAXFLOAT
        anima.duration = 0.5
        loadingIcon.layer.addAnimation(anima, forKey: nil)
    }
    /// 停止所有动画
    private func stopLoadingAnimation() {
        tipView.hidden = false
        loadingIcon.layer.removeAllAnimations()
    } 
}